#include "stdafx.h"
#include "Animation.h"
#include "MessageLoop.h"
#include <memory>

AnimationDelegate::AnimationDelegate()
{

}

AnimationDelegate::~AnimationDelegate()
{

}

Animation::Animation(int max_step, int grain)
	: animating_(false)
	, animate_step_(0)
	, max_step_num_(max_step)
	, grain_(grain)
	, delegate_(NULL)
{
}


Animation::~Animation()
{
}

bool Animation::run()
{

	if (max_step_num_ == 0 || animate_step_ < max_step_num_)
	{
		// ATLTRACE("[%s][%d][%d]\r\n", __FUNCTION__, __LINE__, animate_step_);
		if (step(animate_step_++))
		{
			if (delegate_)
			{
				delegate_->animateStep(this);
			}

			postTask();

			return true;
		}
		else
		{
			animate_step_ = 0;
			animating_ = false;
			if (delegate_)
			{
				delegate_->animateCanceled(this);
			}
		}
	}
	else
	{
		animate_step_ = 0;
		animating_ = false;
		if (delegate_)
		{
			delegate_->animateCompleted(this);
		}
	}

	return true;
}

void Animation::startAnimation()
{
	animating_ = true;
	animate_step_ = 0;
	if (delegate_)
	{
		delegate_->animateStarted(this);
	}

	postTask();
}

int Animation::getMaxStepNum()
{
	return max_step_num_;
}


void Animation::setDelegate(AnimationDelegate* delegate)
{
	delegate_ = delegate;
}

AnimationDelegate* Animation::getDelegate()
{
	return delegate_;
}

void Animation::postTask()
{
	std::shared_ptr<Task> task = std::shared_ptr<Task>(new AnimationTask(this));
	task->setTick(Time::now() + grain_);
	MessageLoop::getInstance().addTask(task);

}

AnimationTask::AnimationTask(Animation* animation)
	: ani_(animation)
{

}

AnimationTask::~AnimationTask()
{

}

bool AnimationTask::run(void* param)
{
	TimeTicks tick = Time::now() - getTick();
	// ATLTRACE("run delay : %u ms \r\n", tick.getTick());
	if (ani_)
	{
		return ani_->run();
	}

	return false;
}
